<?php

/**
 * 入库列表类
 * @copyright   Copyright (c) 2006 - 2010 DZH 友拓软件友拓通
 * @category    基本信息
 * @package   Model
 * @author     庄敏学
 * @version  2.1,2012-07-22
 */

class InstockPublicModel extends RelationCommonModel {
	
	/// 定义真实表名
	protected $tableName = 'instock';
	
	/// 定义表关联
	protected $_link	 = array('detail' => 
									array(
										'mapping_type'	=> HAS_MANY,
										'foreign_key' 	=> 'instock_id',
										'class_name'	=> 'InstockDetail',
									)
								);	
								
	/// 自动验证设置
	protected $_validate	 =	 array(
			array("container_no",'require','require',1),
			array("logistics_id",'validlogistics','require',1,'callbacks'),
			array("real_arrive_date",'require','require',0),
			array('real_arrive_date','validRealArriveDate','require',0,'callbacks'),
			array("get_date",'require','require',0),
			array("go_date",'require','require',0),
			array("arrive_date",'require','require',0),
			array('delivery_fee','currency','valid_money',0),
			array('currency_id','require','require',0),
			array("warehouse_id",'require',"require",1),
			array("",'_validDetail','require',1,'validDetail'),
			array('','validAddInstock','require',1,'callbacks'),
			array('','validFactoryFund','require',1,'callbacks'),
		);	
	protected $_validDetail	 =	 array(
			array("product_id",'require','require',1),
			array('factory_id','require','require',0),
			array('currency_id','require','require',1),
			array("color_id",'require','require',0),
			array("size_id",'require','require',0),
			array("quantity",'z_integer','z_integer',1),
			array("capability",'pst_integer','pst_integer',0),
			array("dozen",'pst_integer','pst_integer',0),
			array("price",'double','double',0),
			array('price','currency','valid_money',0),
			array('per_size','require','require',0),
			array('per_size','double','double',0),
			array('per_capability','double','double',2),
		);	
	protected $_validLogistics = array(
			array("logistics_id",'require','require',1),
	);
	/// 自动填充
	protected $_auto = array(
							array("create_time ", "date", 1, "function", "Y-m-d H:i:s"), // 创建时间	
							array("update_time ", "date", 2, "function", "Y-m-d H:i:s"), // 更新时间					
						);
						
	///物流公司验证	
	public function validlogistics($data){
		//物流公司款项配置为是时  物流公司必填
		if(C('instock.instock_logistics_funds')==1){
			$name	= '_validLogistics';
			return $this->_validSubmit(&$data,$name);
		}
	}
	
	/// 到达日期验证
	public function validRealArriveDate($data){
		if(C('instock.add')==2){
			$go_date			= formatDate($data['go_date']);
			$real_arrive_date	= formatDate($data['real_arrive_date']);
			if($real_arrive_date<$go_date){
				$error['name']	= 'real_arrive_date';
				$error['value']	= L('real_egt_to');
				$this->error[]	= $error;
			}
		}
	}
	
	///验证是否 有汇率 没有汇率时 提示取固定汇率
	public function validRate($data){
		$detail_currency	= array();
		foreach($data['detail'] as $val){
			if($val['currency_id']>0&&$data['currency_id']!=$val['currency_id']){
				$detail_currency[]	= $val['currency_id'];
			}
		}
		$detail_currency	= array_unique($detail_currency);
		if($data['currency_id']>0&&!empty($detail_currency)){
			$rate_type	= C('set_rate_type');
			if($rate_type==2){	//按月
				$date	= date('Y-m',strtotime(formatDate($data['real_arrive_date'])));
				$rate 	= M('rate_info')
							->where("rate_date='".$date."-01' and from_currency_id=".$data['currency_id']." and to_currency_id in (".implode(',',$detail_currency).")")
							->select();
			}elseif($rate_type==3){		//按单据日期
				$date	= date('Y-m-d',strtotime(formatDate($data['real_arrive_date'])));
				$rate 	= M('rate_info')
							->where("rate_date='".$date."' and from_currency_id=".$data['currency_id']." and to_currency_id in (".implode(',',$detail_currency).")")
							->select();	
			}
			foreach($rate as $val){
				$rate_curr	= $val['to_currency_id'];
			}
			
			$diff	= array_diff($detail_currency,(array)$rate_curr);
			if(!empty($diff)){
				$fixed_rate	= M('fixed_rate')->where('from_currency_id='.$data['currency_id'].' and to_currency_id in ('.implode(',',$diff).')')->select();
				$currency	= S('currency');
				$info		= L('instock_rate_error');
				$fixed_rate	= _formatList($fixed_rate);
				foreach($fixed_rate['list'] as $key=>$val){
					$info	.= "\n".$currency[$val['from_currency_id']]['currency_no'].'--'.$currency[$val['to_currency_id']]['currency_no'].'：'.$val['dml_rate'].'';
				}
			
				$error	= array('status'=>3,'info'=>$info,'rate'=>M('rate_info')->getLastSql());
				return $error;
			}
		}
	}
	
	///配置新入库时 规格验证
	public function validAddInstock($data){
		if(C('instock.add')==1){
			$spec	= array();
			foreach($data['detail'] as $key=>$val){
				if($val['product_id']==0||empty($val['product_id'])||$val['mantissa']==2){
					continue;
				}
				$detail_spec = $val['factory_id'].'_'.$val['currency_id'].'_'.$val['product_id'].'_'.$val['color_id'].'_'.$val['size_id'].'_'.$val['capability'].'_'.$val['dozen'];
				if(in_array($detail_spec,$spec)){
					$error['name']	= 'detail['.$key.'][product_id]';
					$error['value']	= L('spec_error');
					$this->error[]	= $error;
				}else{
					$spec[]	= $detail_spec;
				}
			}
		}
	}
	///修改时 厂家款项已结清 不可再新增已结清的厂家 币种数据
	public function validFactoryFund($data){
		if($data['id']>0){
			$factory_fund	= Funds($data['id'],220,'EditPassInfo');
			foreach($data['detail'] as $key=>$val){
				if($val['id']>0){
					$where		= 'id='.$val['id'].' and factory_id='.$val['factory_id'].' and currency_id='.$val['currency_id'];
					$count		= M('instock_detail')->where($where)->count();
					if($count>0){
						continue;
					}
				}
				foreach($factory_fund as $fund){
					if($val['factory_id']==$fund['comp_id']&&$val['currency_id']==$fund['currency_id']){
						$error['name']	= 'detail['.$key.'][factory_id]';
						$error['value']	= L('factory_fund');
						$this->error[]	= $error;
					}
				}
			}
		}
	}
	
	/// 查看
	public function view(){ 
		return $this->getInfoInstock($this->id);
	}
	
	/// 编辑
	public function edit(){
		return $this->getInfoInstock($this->id);
	}
	

	
	///列表
	public function indexSql(){  
		return $this->getInstockListSql(_search_array(_getSpecialUrl($_GET))); 
	}
	
	/**
	 * 取列表
	 * @param string $where
	 * @return array
	 */
	public function getInstockListSql($where=null){
		$count 	= $this->exists('select 1 from instock_detail where instock_id=instock.id and '.getWhere($_POST['detail']))->where(getWhere($_POST['main']))->count();
		$this->setPage($count);
		$ids	= $this->field('id')->exists('select 1 from instock_detail where instock_id=instock.id and '.getWhere($_POST['detail']))->where(getWhere($_POST['main']))->order('instock_no desc')->page()->selectIds();
		$info['from'] 	= 'instock a left join instock_detail b on(a.id=b.instock_id) left join invoice_in c on a.id=c.relation_id';
		$info['group'] 	= ' group by a.id order by instock_no desc';
		$info['where'] 	= ' where a.id in'.$ids;
		$info['field'] 	= 'a.*,a.id as instock_id,count(distinct b.product_id) as product_qn,b.warehouse_id,group_concat(distinct c.id) invoiceIn_id,group_concat(distinct invoice_no) group_relation_no,sum(if(invoice_state=2,0,1)) no_invoice, b.capability as sum_capability, sum(b.quantity) as sum_qn, sum(b.quantity*b.capability*b.dozen) as sun_quantity, sum(b.quantity*b.capability*b.dozen*b.price) as money';
		return  'select '.$info['field'].' from '.$info['from'].$info['where'].$info['group']; 
	}
	
	/**
	 * 入库格式化
	 * @return array
	 */
	public function setPost(){
		$info	= $_POST;
		//修改入库单 设置发票状态
		if(ACTION_NAME=='update'){
			$invoice	= M('invoice_in')->where("relation_id='".$info['id']."' ")->select();
			foreach($invoice as $key=>$val){
				$invoice_factory[$val['factory_id']]	= $val;
			}
		}
		foreach ($info['detail'] as &$value) {
			$value['warehouse_id'] = $info['warehouse_id'];
			!isset($value['capability']) && $value['capability'] =1;
	 		!isset($value['dozen']) && $value['dozen'] =1;
	 		$info['all_quantity']	+= $value['quantity']*$value['capability']*$value['dozen'];
	 		$info['total_size']		+= $value['per_size']*$value['quantity'];
	 		if(C('invoice.factory_from')==1){
	 			!empty($invoice_factory[$value['factory_id']]) && $value['invoice_state']=2;
	 		}else{
	 			!empty($invoice) && $value['invoice_state']=2;
	 		}
	 	}
	 	$info	= $this->setDeliveryPrice($info);
		$this->Mdate	=	$info; 
		return $info;
	}
	
	/**
	 * 计算运费
	 * @param array $info
	 * @return array
	 */
	public function setDeliveryPrice($info){
		if(C('instock.delivery')==2){	//按立方算
			foreach($info['detail'] as &$value){
				$value['delivery_fee_detail'] = ($info['delivery_fee']/$info['total_size'])*($value['per_size']/($value['capability']*$value['dozen']));
			}
		}else{//按数量算
		 	$delivery_price = $info['delivery_fee']/$info['all_quantity'];
		 	foreach ($info['detail'] as &$value) {
		 		$value['delivery_fee_detail'] = $delivery_price ? $delivery_price : 0;
		 	}
		}
		return $info;
	}
	
	/**
	 * 获取入库单信息
	 * @param int $id
	 * @return array
	 */
	public function getInfoInstock($id){
		
		$rs = $this->find($id);  
		//统计根据厂家 币种显示
		if($_GET['comp_id']>0){
			$stat	.=' and a.factory_id='.intval($_GET['comp_id']);
		}
		if($_GET['currency_id']>0){
			$stat	.= ' and a.currency_id='.intval($_GET['currency_id']);
		}
		$sql	=	' select a.*,b.order_no,delivery_fee_detail*quantity*capability*dozen delivery_fee_detail,quantity*per_size as real_per_szie,quantity*per_capability as real_per_capability,
					sum(quantity*capability*dozen) sum_quantity,
					sum(quantity*capability*dozen*price) money 
					from instock_detail a left join orders b on a.orders_id=b.id where instock_id='.$id.$stat.'  group by a.id order by a.id';  
		$rs['detail'] = $this->db->query($sql); 
		$rs['warehouse_id']=$rs['detail'][0]['warehouse_id'];  //取仓库
		if (false === $rs || $rs == null) { // 记录不存在或没权限查看该记录
			halt(L('data_right_error'));
		}
		$rs = _formatListRelation($rs);
		$rs['funds']['factory']	= Funds($id,220,'EditPassInfo');
		$rs['funds']['logistics']	= Funds($id,320,'EditPassInfo');//物流
		//款型
		foreach((array)$rs['detail'] as $key=>$val){
			foreach($rs['funds']['factory'] as $funds){
				if($funds['comp_id']==$val['factory_id']&&$funds['currency_id']==$val['currency_id']){
					$rs['detail'][$key]['fund_state']	= 1;
				}
			}
		}
		return $rs;
	}
	
	/**
	 * 待入库
	 * @return unknown
	 */
	public function waitInstock(){
		$where			= _search().' and '._search_array(_getSpecialUrl($_GET)).' and load_state<2';
		$count			= M('load_container')->where($where)->count();
		$this->setPage($count);
		$ids			= M('load_container')->field('id')->where($where)->page()->selectIds();
		
		$info['from']	= 'load_container a LEFT JOIN load_container_details b ON a.id = b.load_container_id';
		$info['where']	= ' where a.id in '.$ids;
		$info['group']	= ' group by a.id order by a.load_container_no desc';
		$info['field']	= 'load_container_no,container_no,load_date,delivery_date,expect_arrive_date,logistics_id,a.id,
							sum(b.quantity) as sum_qn,
							sum(b.quantity*b.capability*b.dozen) as sun_quantity
							';
		return _formatList($this->query('select '.$info['field'].' from '.$info['from'].$info['where'].$info['group']));
		/*$where && $where = ' and '.$where;
		$info['from'] = 'load_container a LEFT JOIN load_container_details b ON a.id = b.load_container_id ';
		$info['extend'] = ' where  '._search().$where.' and '._search_array(_getSpecialUrl($_GET)).' and load_state<2 ';
		$info['group'] 	= '  group by a.id order by a.load_container_no desc';
		$info['field'] 	= 'load_container_no,container_no,load_date,delivery_date,expect_arrive_date,logistics_id,
						sum(b.quantity) as sum_qn,
						sum(b.quantity*b.capability*b.dozen) as sun_quantity
						';
		$sql	= 'select '.$info['field'].' from '.$info['from'].' '.$info['extend'].$info['group']; 
		$count	=	0;
		$sql_count	= 'select count(distinct(a.id)) as count '.' from '.$info['from'].$info['extend'];
		$list	=	$this->query($sql_count);
		$count	=	$list[0]['count'];
		$info['sql']	=	$sql;
		$info['count']	=	$count; 
		$limit	= _page($count);
		return $this->indexList($limit,$sql);*/
	}
	
	///获取待装柜明细
	public function getLoad(){
		$rs = M('LoadContainer')->find($this->id);  
		$sql	=	' select a.load_container_id,a.orders_id,a.order_details_id,a.currency_id,a.product_id,a.color_id,a.size_id,a.price,a.quantity,a.capability,a.dozen,a.mantissa,a.per_size,a.per_capability,
					b.order_no,b.id as orders_id,b.factory_id,
					sum(quantity*capability*dozen) sum_quantity,
					sum(quantity*capability*dozen*price) money 
					from load_container_details a left join orders b on a.orders_id=b.id where load_container_id='.$this->id.' group by a.id order by a.id';  
		$rs['detail'] = $this->db->query($sql); 
		if (false === $rs || $rs == null) { // 记录不存在或没权限查看该记录
			halt(L('data_right_error'));
		} 
		$rs = _formatListRelation($rs);
		//计算尺寸和重量
		foreach((array)$rs['detail'] as $key=>$val){
			$rs['detail_total']['total_size']	+= $val['quantity']*$val['per_size'];
			$rs['detail_total']['total_capability']+= $val['quantity']*$val['per_capability'];
		}
		$rs['detail_total']['dml_total_size']	= moneyFormat($rs['detail_total']['total_size'],0,C('MONEY_LENGTH'));
		$rs['detail_total']['dml_total_capability']= moneyFormat($rs['detail_total']['total_capability'],0,C('MONEY_LENGTH'));
		return $rs;
	}
}